package com.coda.clouddisk.interceptor;

import com.alibaba.fastjson.JSON;

import com.coda.clouddisk.context.BaseContext;
import com.coda.clouddisk.entity.KesunReturn;
import com.coda.clouddisk.exception.BaseException;
import com.coda.clouddisk.message.MessageContext;
import com.coda.clouddisk.properties.JwtProperties;
import com.coda.clouddisk.utils.JWTUtlis;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前请求是否为controller方法
        if (!(handler instanceof HandlerMethod)) {
            //不是controller中的方法，静态方法直接放行
            return true;
        }

        try {
            //从请求头中获取token
            String token = request.getHeader(jwtProperties.getTokenName());
            //校验jwt令牌
            Claims claims = JWTUtlis.parseJWT(jwtProperties.getSecretKey(), token);
            String id = claims.get("Id").toString();
            log.info("当前员工id：{}", id);

            //匹配redis中的token
            String redisToken = (String) redisTemplate.opsForValue().get(id);
            if (!(redisToken != null || redisToken.equals(token))){
                throw new BaseException(MessageContext.TOKENERROR_CODE,"登录状态异常");
            }

            //将员工id存入线程中
            BaseContext.setCurrentId(id);
//            放行
            return true;
        } catch (NumberFormatException e) {
            //jwt校验失败
            KesunReturn result = new KesunReturn();
            result.setCode(MessageContext.TOKENERROR_CODE);
            result.setMsg(MessageContext.TOKENERROR_MSG);
            //将其转换成json字符串响应前端
            String jsonResult = JSON.toJSONString(result);
            //获取PrintWriter，用于向前端输出数据
            PrintWriter writer = response.getWriter();
            writer.print(jsonResult);
            writer.flush();
            writer.close();
            return false;
        }
    }

    /**
     * 清理用户信息
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
